﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HierarchicalClustering.Metrics;
using HierarchicalClustering.LinkageCriteria;
using TextMining;
using HierarchicalClustering;
using System.Windows.Forms;
using System.IO;

namespace Clustering
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private DocumentsSet _set;
        private BlogReader _reader;
        private HierarchicalClustering.Clustering _clustering;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MetricsComboBox.DataContext = MetricFactory.GetMetricNames();
            LinkageCriteriaComboBox.DataContext = LinkageFactory.GetLinkageNames();

            NumericUpDown control = (NumericUpDown)ClusterNumberWindowsFormsHost.Child;
            control.ValueChanged += new EventHandler(NumericUpDown_ValueChanged);
        }

        private void RunButton_Click(object sender, RoutedEventArgs e)
        {
            double percentage;
            int numOfClusters, numOfDocuments;

            Cursor = System.Windows.Input.Cursors.Wait;
            GetNumericValues(out percentage, out numOfClusters, out numOfDocuments);
            _set = new DocumentsSet();
            _reader = new BlogReader();

            _reader.ReadStopWords("stop_words.txt");
            if (AllDocumentsCheckBox.IsChecked == false)
                _reader.ReadBlog("dataset.txt", _set, numOfDocuments);
            else
                _reader.ReadBlog("dataset.txt", _set);
            _set.RemoveLessImportant(_reader.Documents, percentage);
            LinkedList<Cluster> sample = _set.GetTrainingSample(100);

            _clustering = new HierarchicalClustering.Clustering(
                MetricsComboBox.SelectedValue.ToString(), LinkageCriteriaComboBox.SelectedValue.ToString(),
                sample, numOfClusters, _reader.Documents);
            _clustering.CreateClusters();

            SetResults(_clustering);
            Cursor = System.Windows.Input.Cursors.Arrow;
        }

        private void SetResults(HierarchicalClustering.Clustering clustering)
        {
            ClustersListBox.DataContext = clustering.Clusters.First.Value.Documents;
            groupBox6.Visibility = Visibility.Visible;
            ClustersListBox.Visibility = Visibility.Visible;
            ExportButton.Visibility = Visibility.Visible;

            NumericUpDown control = (NumericUpDown)ClusterNumberWindowsFormsHost.Child;
            control.Maximum = clustering.Clusters.Count;
            control.Value = 1;
        }

        private void GetNumericValues(out double percentage, out int numOfclusters, out int numOfDocuments)
        {
            NumericUpDown control = (NumericUpDown)PercentageWindowsFormsHost.Child;
            percentage = (double)control.Value;
            control = (NumericUpDown)NumOfClustersWindowsFormsHost.Child;
            numOfclusters = (int)control.Value;
            control = (NumericUpDown)NumOfDocumentsWindowsFormsHost.Child;
            numOfDocuments = (int)control.Value;
        }

        private void NumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            NumericUpDown control = (NumericUpDown)sender;
            ClustersListBox.DataContext = _clustering.Clusters.ElementAt((int)control.Value - 1).Documents;
        }

        private void AllDocumentsCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            NumOfDocumentsWindowsFormsHost.IsEnabled = false;
        }

        private void AllDocumentsCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            NumOfDocumentsWindowsFormsHost.IsEnabled = true;
        }

        private void ClustersListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ClustersListBox.SelectedIndex < 0)
                return;

            Document document = (Document)ClustersListBox.SelectedValue;
            DocumentViewer viewer = new DocumentViewer(document);
            viewer.Show();
        }

        private void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            bool flag;
            int i = 0;
            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();

            dialog.Filter = "Text file (*.txt)|*.txt";
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog().Value != true)
                return;
            using (StreamWriter writer = new StreamWriter(dialog.FileName))
            {
                foreach(Cluster cluster in _clustering.Clusters)
                {
                    writer.WriteLine("Cluster " + (i + 1).ToString() + ":");
                    flag = true;
                    foreach (Document document in cluster.Documents)
                    {
                        if (flag == false)
                            writer.Write(", ");
                        flag = false;
                        writer.Write(document.Id);
                    }
                    writer.WriteLine();
                    writer.WriteLine();
                    i++;
                }
            }
        }
    }
}
